//
//  UIImage+ZChangeTineColor.m
//  CoreAnimation
//
//  Created by 张国文 on 16/12/9.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "UIImage+ZChangeTineColor.h"

@implementation UIImage (ZChangeTineColor)

/**
 *  kCGBlendModeDestinationIn R = D * Sa，保留原始图片的透明度，D为目标颜色，Sa为原始图片的alpha。
 kCGBlendModeDestinationIn 保留原始图片的灰度信息(就是渐变效果)，但是不会保留原始图片的透明度。
 因此如果想要对渐变图片进行重新绘制颜色，将这两种模式混合使用，这样既可以保留原始图片的灰度信息，也可以保留原始图片的透明度。
 */

- (UIImage *) imageWithTintColor:(UIColor *)tintColor

{
    
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
    
}

- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor

{
    
    return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
    
}

- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode

{
    
    //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    
    [tintColor setFill];
    
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    
    UIRectFill(bounds);
    
    //Draw the tinted image in context
    
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    
    if (blendMode != kCGBlendModeDestinationIn) {
        
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
        
    }
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return tintedImage;
    
}



@end
